﻿Imports System.Text

''' <summary>
''' スネークケース文字変換
''' </summary>
''' <remarks>#97　MySQL対応</remarks>
Public Class SnakeCaseFormConverter
    Inherits StringFormConverter

    Const TABLE_PREFIX As String = "T_"
    Const DELIMITER As String = "_"

    Public Overrides Function ToNameSpace(t As System.Type) As String
        Return Me.ToSnakeCase(MyBase.ToNameSpace(t))
    End Function

    Public Overrides Function ToTable(t As System.Type) As String
        Return TABLE_PREFIX & Me.ToSnakeCase(MyBase.ToTable(t))
    End Function

    Public Overrides Function ToColumn(name As String) As String
        Return Me.ToSnakeCase(MyBase.ToColumn(name))
    End Function

    Public Overrides Function ToPrefix(name As String) As String
        If String.IsNullOrEmpty(name) Then Return String.Empty
        Return Me.ToSnakeCase(name) & DELIMITER
    End Function

    Public Function ToSnakeCase(name As String) As String
        Dim s As New StringBuilder

        Dim isPrevUpper As Boolean = True
        For Each item In name
            If Char.IsUpper(item) Then
                '1つ前の文字が大文字なら、そのまま結合
                'それ以外は単語区切り記号を追加してから結合
                If isPrevUpper = False Then s.Append(DELIMITER)
                s.Append(item)
                isPrevUpper = True
            ElseIf Char.IsLower(item) Then
                s.Append(Char.ToUpper(item))
                isPrevUpper = False
            Else
                '#83　「#80の命名規則がOracle書式で正しく動作しない」Fix
                '記号はそのまま使用する。
                s.Append(item)
                isPrevUpper = True
            End If
        Next

#If DEBUG Then
        If s.Length > 30 Then Debug.Print(String.Format("[WARN] 30文字を超えました。（変換前：{0}、変換後：{1}、長さ：{2}）", name, s, s.Length))
#End If

        Return s.ToString
    End Function

    Public Overrides Function Convert(name As String) As String
        Return Me.ToSnakeCase(name)
    End Function

End Class
